package com.eddie.hhcook;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.eddie.hhcook.adapter.NoticeAdapter;
import com.eddie.hhcook.annotation.ContentView;
import com.eddie.hhcook.annotation.ViewInject;
import com.eddie.hhcook.annotation.ViewUtils;
import com.eddie.hhcook.base.BaseActivity;
import com.eddie.hhcook.entity.Notice;
import com.eddie.hhcook.utils.Constant;
import com.eddie.hhcook.utils.HHPreferences;
import com.eddie.hhcook.utils.ListViewAnimationAdapter;
import com.eddie.hhcook.utils.LogUtils;
import com.eddie.hhcook.utils.ShareUtils;
import com.eddie.hhcook.utils.ToastFactory;
import com.eddie.hhcook.view.PullToRefreshListView;
import com.eddie.hhcook.view.SharePopwindow;
import com.eddie.hhcook.view.SlidingMenu;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity implements View.OnClickListener,AdapterView.OnItemClickListener{

    private static final String TAG = MainActivity.class.getSimpleName();

    @ViewInject(R.id.h_menu)
    private SlidingMenu menu;
    @ViewInject(R.id.home_listview)
    private PullToRefreshListView activity_list;
    @ViewInject(R.id.login_btn)
    private TextView login_btn;
    @ViewInject(R.id.user_img)
    private ImageView user_img;
    @ViewInject(R.id.wait_loading)
    private LinearLayout wait_loading;
    @ViewInject(R.id.home_left_menu)
    private ImageView home_left_menu;

    private List<Notice> notices;
    private long mExitTime;
    private NoticeAdapter adapter;
    private SharePopwindow sharePopwindow;
    private Notice notice;
    private ListViewAnimationAdapter listViewAnimationAdapter;
    private boolean isRefresh = false;

    @Override
    public void initView() {
       // initSystemBar();
        ViewUtils.inject(this);
        wait_loading.setVisibility(View.VISIBLE);
        notices = new ArrayList<Notice>();
        CheckHtmlCache();
    }

    @Override
    public void setListener() {
        user_img.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        home_left_menu.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.home_left_menu:
                menu.toggle();
                break;
            case R.id.login_btn:
                startActivity(new Intent(this,LoginActivity.class));
                break;
            case R.id.user_img:
                if (HHcookApp.getInstance().getmTencent() != null){
                    startActivity(new Intent(this,PersonCenterActivity.class));
                }else{
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
        }
    }

    /**
     * 检查是否有缓存
     */
    public void CheckHtmlCache(){
        String d = HHPreferences.getInstance().redToHtml(this);
        LogUtils.d(TAG, "d == " + d);
        if (!TextUtils.isEmpty(d)){
            analyzeHtml(d);
        }else{
            getNoticeData();
        }
    }

    /**
     * 获取网络数据
     */
    public void getNoticeData(){
        StringRequest request = new StringRequest(
                Request.Method.POST, Constant.BASE_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String d) {
                //先清除cache,然后cache
                LogUtils.d(TAG,"volley = "+ d);
                HHPreferences.getInstance().clearHtml(MainActivity.this);
                HHPreferences.getInstance().writeToHtml(MainActivity.this,d);
                analyzeHtml(d);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
            }
        });
        HHcookApp.getInstance().getRequestQueue().add(request);
    }


    /**
     * 解析html
     * @param d
     */
    public  void  analyzeHtml(String d){
        if (isRefresh){
            notices.clear();
        }
        if (!TextUtils.isEmpty(d)){
            wait_loading.setVisibility(View.GONE);
            Document doc = Jsoup.parse(d);
            Element lunch = doc.select("div.zzw_item_3").first();
            Element morning = doc.select("div.zzw_item_2").first();
            Element afternoon = doc.select("div.zzw_item_4").first();
            Element yexiao = doc.select("div.zzw_item_1").first();
            Element evening = doc.select("div.zzw_item_5").first();

            Elements lunch_lis = lunch.getElementsByTag("li");
            Elements morning_lis = morning.getElementsByTag("li");
            Elements afternoon_lis = afternoon.getElementsByTag("li");
            Elements yexiao_lis = yexiao.getElementsByTag("li");
            Elements evening_lis = evening.getElementsByTag("li");
            for(int i = 0;i<lunch_lis.size();i++){
                Element lunch_li = lunch_lis.get(i);
                Element morning_li = morning_lis.get(i);
                Element afternoon_li = afternoon_lis.get(i);
                Element yexiao_li = yexiao_lis.get(i);
                Element evening_li = evening_lis.get(i);
                setNoticeData(lunch_li,3);
                setNoticeData(morning_li,2);
                setNoticeData(afternoon_li,4);
                setNoticeData(yexiao_li,1);
                setNoticeData(evening_li, 5);
            }

        }
        adapter = new NoticeAdapter(MainActivity.this,notices);
        listViewAnimationAdapter = new ListViewAnimationAdapter(adapter);
        listViewAnimationAdapter.setAbsListView(activity_list);
        listViewAnimationAdapter.getViewAnimator().setAnimationDurationMillis(500);
        listViewAnimationAdapter.getViewAnimator().setAnimationDelayMillis(500);
        activity_list.setAdapter(listViewAnimationAdapter);

        adapter.setShareListener(new NoticeAdapter.ShareListener() {
            @Override
            public void onShare(Notice notice) {
                LogUtils.d(TAG, notice.getDesc());
                MainActivity.this.notice = notice;
                sharePopwindow = new SharePopwindow(MainActivity.this);
                sharePopwindow.setOnSharePopClickListener(new WQSShareListener());
                sharePopwindow.showAtLocation(
                        findViewById(R.id.home_share_layout),
                        Gravity.BOTTOM, 0, 0);
            }
        });
        activity_list.setOnItemClickListener(MainActivity.this);
        activity_list.setonRefreshListener(new PullToRefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                getNoticeData();
                ToastFactory.show(MainActivity.this, getResources().getString(R.string.no_data));
                adapter.notifyDataSetChanged();
                activity_list.onRefreshComplete();
            }
        });
    }

    /**
     * 分享至QQ 微信 微博
     */
    public class WQSShareListener implements SharePopwindow.OnSharePopClickListener {

        @Override
        public void click(int type) {
            try{
                switch (type){
                    case 2:
                        ShareUtils.shareTO(MainActivity.this,2,notice);
                        break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param
     * @param e
     * @param type
     */
    public void setNoticeData(Element e,int type){
        Notice notice = new Notice();
        notice.setName(e.getElementsByTag("a").attr("title"));
        notice.setUrl(e.getElementsByTag("a").attr("href"));
        notice.setImage(e.getElementsByTag("img").attr("src"));
        notice.setDesc(e.getElementsByTag("strong").text());
        notice.setFunction(e.getElementsByTag("span").text());
        switch (type){
            case 1:
                notice.setType(getResources().getString(R.string.ve_type1));
                break;
            case 2:
                notice.setType(getResources().getString(R.string.ve_type2));
                break;
            case 3:
                notice.setType(getResources().getString(R.string.ve_type3));
                break;
            case 4:
                notice.setType(getResources().getString(R.string.ve_type4));
                break;
            case 5:
                notice.setType(getResources().getString(R.string.ve_type5));
                break;
        }
            notices.add(notice);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //mManager = RadarSearchManager.getInstance();
        Intent intent = new Intent(MainActivity.this,NoticeContentActivity.class);
        intent.putExtra("url", notices.get(position).getUrl());
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastFactory.getToast(this, getResources().getString(R.string.main_exit)).show();
                mExitTime = System.currentTimeMillis();
            } else {
                HHcookApp.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * ״̬��
     */
    private void initSystemBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.red);
            SystemBarTintManager.SystemBarConfig config = tintManager.getConfig();
        }
    }
}
